package com.dong.boot.service;

import com.dong.boot.mapper.DepartmentMapper;
import com.dong.boot.model.Department;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class DepartmentService {
    @Autowired
    DepartmentMapper departmentMapper;

    public List<Department> getAllDepartment() {
        return departmentMapper.getAllDepartmentsByParentId(-1);
    }

    public int addDepartment(Department department) {
        departmentMapper.addDep(department);
        return department.getResult();
    }

    @Transactional
    public Integer deleteDepartment(Department dep) {
        Integer id = dep.getId();
        //查询该部门下是否父部门
        Department department = departmentMapper.selectByPrimaryKey(id);
        if (department.getParent()){
            return 1; //提示父部门无法删除
        }

        //查询父部门下是否只有本部门
        Integer count = departmentMapper.selectByParentId(dep.getParentId());
        if (count == 1){
            Department updateDep = new Department();
            updateDep.setId(dep.getParentId());
            updateDep.setParent(false);
            departmentMapper.updateByPrimaryKeySelective(updateDep);
            departmentMapper.deleteByPrimaryKey(id);
        }
        return 0;
    }
}
